################################################################
#####
#####   Input: Raw data from Deltapoll
#####   Output: Reshaped and recoded data for analysis
#####

setwd(dirname(rstudioapi::getActiveDocumentContext()$path))
rm(list=ls())

library(data.table)
library(tidyverse)
library(questionr)

# Load data -----------------------------------------------------------------------
load("data/deltapoll_data.Rdata")

# Reshape data from wide to long -----------------------------------------------------------------------
to_keep <- subset(df, select = c(1, 106:198))
df_to_keep <- subset(df, select = c(1:105,199:211))

a_cases <- to_keep %>%
  filter(Crisis_Dum == 1) %>%
  select(contains("A"), ResponseID, Q1SPLIT) %>%
  rename_at(vars(contains("A")), ~str_remove(., "A")) %>%
  mutate(Condition = "Security") %>%
  rename(Q1SPLIT = Q1SPLIT)

b_cases <- to_keep %>%
  filter(Crisis_Dum == 2) %>%
  select(contains("B"), ResponseID, Q2SPLIT) %>%
  rename_at(vars(contains("B")), ~str_remove(., "B")) %>%
  mutate(Condition = "Health") %>%
  rename(Q1SPLIT = Q2SPLIT)
  
c_cases <- to_keep %>%
  filter(Crisis_Dum == 3) %>%
  select(contains("C") & !contains("risis_Dum"), ResponseID, Q3SPLIT) %>%
  rename_at(vars(contains("C")), ~str_remove(., "C")) %>%
  mutate(Condition = "Economic") %>%
  rename(Q1SPLIT = Q3SPLIT)

d_cases <- to_keep %>%
  filter(Crisis_Dum == 4) %>%
  select(contains("D") & !contains("risis_Dum"), ResponseID) %>%
  rename_at(vars(contains("D")), ~str_remove(., "D")) %>%
  mutate(Condition = "Control", 
         Q1_1_1 = NA, 
         Q1_1_2 = NA,
         Q1_1_3 = NA, 
         Q1_1_4 = NA, 
         Q1_1_5 = NA, 
         Q1_1_6 = NA, 
         Q1_1_7 = NA, 
         Q1_1_8 = NA, 
         Q1_1_9 = NA, 
         Q1_1_10 = NA, 
         Q1_1_99 = NA, 
         Q1_2_1 = NA,
         Q1_2_2 = NA, 
         Q1_2_3 = NA, 
         Q1_2_DK = NA, 
         Q1SPLIT = NA) %>%
  rename(ResponseID = ResponseI) %>%
  select(!Q1A_2_K & !Q1B_2_K & !Q1C_2_K)

df <- rbind(a_cases, b_cases, c_cases, d_cases)

stacked_data <- merge(df, df_to_keep, by = c("ResponseID"))

# Recode variables -----------------------------------------------------------------
## Gender
stacked_data$gender <- factor(NA, levels = c("Man", "Woman"))
stacked_data$gender[stacked_data$QDP1==1] <- "Man"
stacked_data$gender[stacked_data$QDP1==2] <- "Woman"

## Aggregate traits 
stacked_data <- stacked_data %>%
  mutate(feminine_traits = if_else(Q2_2 == 1 | Q2_5 == 1 | Q2_8 == 1 | Q2_9 == 1, 1, 0,),
         masculine_traits = if_else(Q2_1 == 1 | Q2_6 == 1 | Q2_7 == 1, 1, 0), 
         neutral_traits = if_else(Q2_3 == 1 | Q2_4 == 1, 1, 0))

# Save reshaped data ---------------------------------------
save(stacked_data, file = "data/reshaped_data.Rdata")


